﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using LeoK.Common;
using LeoK.TM.Entity;
using MySql.Data.MySqlClient;
using Telerik.Windows.Controls;

namespace LeoK.TM
{
    /// <summary>
    /// TimeLineManager.xaml 的交互逻辑
    /// </summary>
    public partial class TimeLineManager : UserControl
    {
        private List<TM_Task> _Tasks;
        private LeoKDataGrid<TM_TimeLine> _leoKDataGrid;
        private GridViewComboBoxColumn _taskCol;

        public TimeLineManager()
        {
            InitializeComponent();

            _leoKDataGrid = new LeoKDataGrid<TM_TimeLine>();
            layout.Children.Add(_leoKDataGrid);

            _leoKDataGrid.BeforeGeneratingColumn = BeforeGeneratingColumn;
            Loaded += async (sender, args) =>
            {
                await LoadTaskData();
                DataSpanSelector.SelectionChanged();
            };

            DataSpanSelector.SelectionChanged = () =>
            {
                string filter = " WHERE StartTime>=@StartDate AND StartTime<=@EndDate";
                List<MySqlParameter> paras = new List<MySqlParameter>();
                paras.Add(new MySqlParameter("StartDate", DataSpanSelector.StartDate));
                paras.Add(new MySqlParameter("EndDate", DataSpanSelector.EndDate));

                _leoKDataGrid.LoadData(filter, paras);
            };
        }

        private bool BeforeGeneratingColumn(GridViewAutoGeneratingColumnEventArgs e)
        {
            bool result = false;

            if (e.Column.UniqueName == "TID")
            {
                _taskCol = new GridViewComboBoxColumn();
                _taskCol.UniqueName = "TID";
                _taskCol.Header = "任务";
                _taskCol.IsComboBoxEditable = false;
                _taskCol.DisplayMemberPath = "Name";
                _taskCol.SelectedValueMemberPath = "ID";
                _taskCol.ItemsSource = _Tasks;

                e.Column = _taskCol;
                result = true;
            }

            return result;
        }

        public async Task LoadTaskData()
        {
            using (MySqlDB db = new MySqlDB())
            {
                _Tasks = await db.QueryObjs<TM_Task>("SELECT * FROM TM_Task");
                if (_taskCol != null)
                {
                    _taskCol.ItemsSource = _Tasks;
                }
            }
        }

        private void btnRefresh_Click(object sender, MouseButtonEventArgs e)
        {
            DataSpanSelector.SelectionChanged();
        }
    }
}
